package com.rich.util;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

public class BlueToothTestUtils {
	private Context mContext;
	private String mNameList = "";
	private boolean mBlueFlag = false;
	private BluetoothAdapter mAdapter;
	private Message msg;
	HandlerThread mBlueThread = new HandlerThread("blueThread");
	private BlueHandler mBlueHandler;

	public BlueToothTestUtils(Context context) {
		mContext = context;
	}

	public void getBtDevice() {
		mAdapter = BluetoothAdapter.getDefaultAdapter();
		mBlueThread.start();
		mBlueHandler = new BlueHandler(mBlueThread.getLooper());
		mBlueHandler.post(bluerunnable);
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			mBlueHandler.removeCallbacks(bluerunnable);
			IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
			mContext.registerReceiver(mReceiver, filter);
			IntentFilter filter_finished = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
			mContext.registerReceiver(mReceiver, filter_finished);
			mBlueFlag = true;
			while (mAdapter.startDiscovery() == false) {
				mAdapter.startDiscovery();
			}
		}
	};

	Runnable myRunnable = new Runnable() {
		@Override
		public void run() {
			if (mAdapter.enable()) {
				mHandler.removeCallbacks(myRunnable);
				init();
			} else {
				mHandler.post(myRunnable);
			}
		}
	};

	private void init() {
		mAdapter.enable();
		if (mAdapter.isEnabled() == true) {
			msg = mHandler.obtainMessage();
			msg.sendToTarget();
		} else {
			mBlueHandler.postDelayed(bluerunnable, 3000);
		}
	}

	BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					mNameList += device.getName() + "--" + "MAC:" + device.getAddress() + "\n";

				}
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

			}
		}
	};

	class BlueHandler extends Handler {
		public BlueHandler() {
		}

		public BlueHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
		}
	}

	Runnable bluerunnable = new Runnable() {
		@Override
		public void run() {
			init();
		}
	};
}
